// index.js
import Dialog from '@vant/weapp/dialog/dialog';
const { mpserverless } = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentDate: new Date().getTime(), //获取当前日期
    currentYear: new Date().getFullYear(),  //获取当前年份
    currentMonth: new Date().getMonth() + 1, //获取当前月份
    minDate: new Date(2018, 4, 30).getTime(),  //日期选择的最小日期
    searchValue: '',   //搜索内容
    isShow: false,  //是否展示日期选择
    newAllData: [],   //所有新数据
    headInfo: [],     //渲染账单数组
    monthOutcome: 0.00,    //月支出
    monthIncome: 0.00,     //月收入
    monthBalance: 0.00,     //月剩余
    isDisplay: true,          //是否显示骨架屏
    isEmpty: false,           //数据是否为空
  },

  changeMonth(event) {
    this.setData({ isEmpty: false });
    wx.getStorage({
      key: 'allData',
      success: (result) => {
        let newArr = [];
        newArr = result.data;
        let timeStamp = this.timestampToTime(event.detail);
        //按月份计算月收入支出
        let mOut_tem = 0;  //月支出
        let mIn_tem = 0;   //月收入
        let mBal_tem = 0;   //月剩余
        let nowDateStamp = event.detail;   //当前月份第一天时间戳
        let nextDateStamp = new Date(timeStamp.substring(0, 4), timeStamp.substring(4)).getTime();  //当前月份最后一天时间戳
        let info_tem = [];    //临时接收数组
        for (let i = 0; i < newArr.length; i++) {
          if (newArr[i].payDateStamp >= nowDateStamp && newArr[i].payDateStamp < nextDateStamp) {
            info_tem.push(newArr[i]);
            mOut_tem += parseFloat(newArr[i].expenditure);
            mIn_tem += parseFloat(newArr[i].income);
            mBal_tem += parseFloat(newArr[i].balance);
          } else {
            continue;
          }
        }
        if (info_tem != '') {
          this.setData({
            headInfo: info_tem,
            monthOutcome: mOut_tem.toFixed(2),
            monthIncome: mIn_tem.toFixed(2),
            monthBalance: mBal_tem.toFixed(2),
            currentYear: timeStamp.substring(0, 4),
            currentMonth: timeStamp.substring(4),
            isDisplay: false,
            isShow: false
          })
        } else {
          this.setData({
            headInfo: info_tem,
            monthOutcome: mOut_tem.toFixed(2),
            monthIncome: mIn_tem.toFixed(2),
            monthBalance: mBal_tem.toFixed(2),
            currentYear: timeStamp.substring(0, 4),
            currentMonth: timeStamp.substring(4),
            isDisplay: false,
            isShow: false,
            isEmpty: true
          })
        }
      },
      fail: () => { },
      complete: () => { }
    });

  },
  showTime() {
    this.setData({
      isShow: true
    })
  },
  onClose() {
    this.setData({ isShow: false });
  },
  toAddPay() {
    let Authorize;
    wx.getStorage({
      key: 'Authorized',
      success: (result) => {
        Authorize = result.data.isAuthorized;
        if (Authorize) {
          wx.navigateTo({
            url: '../addPays/addPays'
          })
        } else {
          Dialog.confirm({
            title: '乖乖',
            message: '微信授权登录后才能正常使用该功能噢',
            confirmButtonText: '去登录',
            cancelButtonText: '等会再登'
          }).then(() => {
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }).catch(() => { });
        }
      },
      fail: (e) => {
        Dialog.confirm({
          title: '乖乖',
          message: '微信授权登录后才能正常使用该功能噢',
          confirmButtonText: '去登录',
          cancelButtonText: '等会再登'
        }).then(() => {
          wx.switchTab({
            url: '/pages/mine/mine',
          })
        }).catch(() => { });
      },
      complete: () => { }
    });
  },
  timestampToTime(time) {
    //时间戳转换
    // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var date = new Date(time);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    let d = date.getDate();
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();
    MM = MM < 10 ? "0" + MM : MM;
    d = d < 10 ? "0" + d : d;
    h = h < 10 ? "0" + h : h;
    m = m < 10 ? "0" + m : m;
    s = s < 10 ? "0" + s : s;
    // return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    // return y + "-" + MM + "-" + d;
    return y + '' + MM;
  },
  deletePay(e) {
    const { position, instance } = e.detail;
    let payId = e.target.dataset.id;
    switch (position) {
      case 'left':
        wx.showToast({
          title: '很爱你哟~♥',
          icon: 'none',
        });
        instance.close();
        break;
      case 'cell':
        instance.close();
        break;
      case 'right':
        instance.close();
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          mpserverless.db.collection('account').deleteOne({
            _id: payId
          }).then(res => {
            if (res.affectedDocs == 1) {
              getApp().globalData.isFreash = true;
              this.onShow();
            } else {
              wx.showToast({
                title: '出现问题啦！',
                icon: 'none',
              });
            }
          }).catch(() => {
            wx.showToast({
              title: '出现问题啦！',
              icon: 'none',
            });
          })
        }).catch(() => { instance.close(); });
        break;
    }
  },
  onLoad() {
    
  },
  /*每次显示页面调用*/
  onShow() {
    let openid = getApp().globalData.openId;
    let isFreash = getApp().globalData.isFreash;

    if (openid == '') {
      //回调函数获取openid
      getApp().openidCallback = openId => {
        openid = openId;
        if (isFreash) {
          //获取并处理所有pays
          mpserverless.db.collection('account')
            .find({
              'openId': openid
            }, { sort: { 'payDateStamp': -1 } })
            .then(res => {
              let headInfo_tem = res.result;
              let newArr = []; //接收数据处理数组
              for (let i = 0; i < headInfo_tem.length;) {
                let flag = 0;  //记录一天有几笔帐
                let duixiang = {};   //临时对象
                let temp = [];       //临时数组
                let detailInfo_tem = {};  //临时详细数据
                let balance_tem = 0;    //每日余额
                let outconme_tem = 0;    //每日支出
                let income_tem = 0    //每日收入
                headInfo_tem[i].detailInfo.isPay ? outconme_tem = parseFloat(headInfo_tem[i].detailInfo.payMoney) : income_tem = parseFloat(headInfo_tem[i].detailInfo.payMoney);
                duixiang.payDate = headInfo_tem[i].payDate;
                duixiang.payDateStamp = headInfo_tem[i].payDateStamp;
                //详细数据对象
                detailInfo_tem.payId = headInfo_tem[i]._id;
                detailInfo_tem.expenditureType = headInfo_tem[i].detailInfo.expenditureType;
                detailInfo_tem.isPay = headInfo_tem[i].detailInfo.isPay;
                detailInfo_tem.payMoney = headInfo_tem[i].detailInfo.payMoney;
                detailInfo_tem.remark = headInfo_tem[i].detailInfo.remark;
                detailInfo_tem.payTypeIcon = headInfo_tem[i].detailInfo.payTypeIcon;
                temp.push(detailInfo_tem);
                for (let j = i + 1; j < headInfo_tem.length; j++) {
                  if (headInfo_tem[i].payDate == headInfo_tem[j].payDate) {
                    flag++;
                    detailInfo_tem = {};
                    detailInfo_tem.payId = headInfo_tem[j]._id;
                    detailInfo_tem.expenditureType = headInfo_tem[j].detailInfo.expenditureType;
                    detailInfo_tem.isPay = headInfo_tem[j].detailInfo.isPay;
                    detailInfo_tem.payMoney = headInfo_tem[j].detailInfo.payMoney;
                    detailInfo_tem.remark = headInfo_tem[j].detailInfo.remark;
                    detailInfo_tem.payTypeIcon = headInfo_tem[j].detailInfo.payTypeIcon;
                    temp.push(detailInfo_tem);
                    if (headInfo_tem[j].detailInfo.isPay) {
                      outconme_tem = outconme_tem + parseFloat(headInfo_tem[j].detailInfo.payMoney);
                    } else {
                      income_tem = income_tem + parseFloat(headInfo_tem[j].detailInfo.payMoney);
                    }
                  } else {
                    break;
                  }
                }
                balance_tem = income_tem - outconme_tem;
                duixiang.balance = balance_tem.toFixed(2);
                duixiang.expenditure = outconme_tem.toFixed(2);
                duixiang.income = income_tem.toFixed(2);
                duixiang.detailInfo = temp;
                newArr.push(duixiang);
                i = i + flag + 1;
              }
              this.setData({
                newAllData: newArr
              })

              //将所有数据按月份分开
              let nowDateStamp = new Date(this.data.currentYear, this.data.currentMonth - 1).getTime();
              let nextDateStamp = new Date(this.data.currentYear, this.data.currentMonth).getTime();
              let info_tem = [];
              let mOut_tem = 0;  //月支出
              let mIn_tem = 0;   //月收入
              let mBal_tem = 0;   //月剩余
              for (let i = 0; i < newArr.length && newArr[i].payDateStamp >= nowDateStamp && newArr[i].payDateStamp < nextDateStamp; i++) {
                info_tem.push(newArr[i]);
                mOut_tem += parseFloat(newArr[i].expenditure);
                mIn_tem += parseFloat(newArr[i].income);
                mBal_tem += parseFloat(newArr[i].balance);
              }
              if (info_tem != '') {
                this.setData({
                  headInfo: info_tem,
                  monthOutcome: mOut_tem.toFixed(2),
                  monthIncome: mIn_tem.toFixed(2),
                  monthBalance: mBal_tem.toFixed(2),
                  isDisplay: false,
                  isEmpty: false
                })
              } else {
                this.setData({
                  headInfo: info_tem,
                  monthOutcome: mOut_tem.toFixed(2),
                  monthIncome: mIn_tem.toFixed(2),
                  monthBalance: mBal_tem.toFixed(2),
                  isDisplay: false,
                  isEmpty: true
                })
              }

              //将所有数据存储下来
              wx.setStorage({
                key: 'allData',
                data: newArr,
                success: (result) => { },
                fail: (e) => { console.error(e); },
              });
            })
            .catch(console.error);
          getApp().globalData.isFreash = false;                //全局置为false
        } else { }
      }
    } else {
      if (isFreash) {
        //获取并处理所有pays
        mpserverless.db.collection('account')
          .find({
            'openId': openid
          }, { sort: { 'payDateStamp': -1 } })
          .then(res => {
            let headInfo_tem = res.result;
            let newArr = []; //接收数据处理数组
            for (let i = 0; i < headInfo_tem.length;) {
              let flag = 0;  //记录一天有几笔帐
              let duixiang = {};   //临时对象
              let temp = [];       //临时数组
              let detailInfo_tem = {};  //临时详细数据
              let balance_tem = 0;    //每日余额
              let outconme_tem = 0;    //每日支出
              let income_tem = 0    //每日收入
              headInfo_tem[i].detailInfo.isPay ? outconme_tem = parseFloat(headInfo_tem[i].detailInfo.payMoney) : income_tem = parseFloat(headInfo_tem[i].detailInfo.payMoney);
              duixiang.payDate = headInfo_tem[i].payDate;
              duixiang.payDateStamp = headInfo_tem[i].payDateStamp;
              //详细数据对象
              detailInfo_tem.payId = headInfo_tem[i]._id;
              detailInfo_tem.expenditureType = headInfo_tem[i].detailInfo.expenditureType;
              detailInfo_tem.isPay = headInfo_tem[i].detailInfo.isPay;
              detailInfo_tem.payMoney = headInfo_tem[i].detailInfo.payMoney;
              detailInfo_tem.remark = headInfo_tem[i].detailInfo.remark;
              detailInfo_tem.payTypeIcon = headInfo_tem[i].detailInfo.payTypeIcon;
              temp.push(detailInfo_tem);
              for (let j = i + 1; j < headInfo_tem.length; j++) {
                if (headInfo_tem[i].payDate == headInfo_tem[j].payDate) {
                  flag++;
                  detailInfo_tem = {};
                  detailInfo_tem.payId = headInfo_tem[j]._id;
                  detailInfo_tem.expenditureType = headInfo_tem[j].detailInfo.expenditureType;
                  detailInfo_tem.isPay = headInfo_tem[j].detailInfo.isPay;
                  detailInfo_tem.payMoney = headInfo_tem[j].detailInfo.payMoney;
                  detailInfo_tem.remark = headInfo_tem[j].detailInfo.remark;
                  detailInfo_tem.payTypeIcon = headInfo_tem[j].detailInfo.payTypeIcon;
                  temp.push(detailInfo_tem);
                  if (headInfo_tem[j].detailInfo.isPay) {
                    outconme_tem = outconme_tem + parseFloat(headInfo_tem[j].detailInfo.payMoney);
                  } else {
                    income_tem = income_tem + parseFloat(headInfo_tem[j].detailInfo.payMoney);
                  }
                } else {
                  break;
                }
              }
              balance_tem = income_tem - outconme_tem;
              duixiang.balance = balance_tem.toFixed(2);
              duixiang.expenditure = outconme_tem.toFixed(2);
              duixiang.income = income_tem.toFixed(2);
              duixiang.detailInfo = temp;
              newArr.push(duixiang);
              i = i + flag + 1;
            }
            this.setData({
              newAllData: newArr
            })

            //将所有数据按月份分开
            let nowDateStamp = new Date(this.data.currentYear, this.data.currentMonth - 1).getTime();
            let nextDateStamp = new Date(this.data.currentYear, this.data.currentMonth).getTime();
            let info_tem = [];
            let mOut_tem = 0;  //月支出
            let mIn_tem = 0;   //月收入
            let mBal_tem = 0;   //月剩余
            for (let i = 0; i < newArr.length && newArr[i].payDateStamp >= nowDateStamp && newArr[i].payDateStamp < nextDateStamp; i++) {
              info_tem.push(newArr[i]);
              mOut_tem += parseFloat(newArr[i].expenditure);
              mIn_tem += parseFloat(newArr[i].income);
              mBal_tem += parseFloat(newArr[i].balance);
            }
            if (info_tem != '') {
              this.setData({
                headInfo: info_tem,
                monthOutcome: mOut_tem.toFixed(2),
                monthIncome: mIn_tem.toFixed(2),
                monthBalance: mBal_tem.toFixed(2),
                isDisplay: false,
                isEmpty: false
              })
            } else {
              this.setData({
                headInfo: info_tem,
                monthOutcome: mOut_tem.toFixed(2),
                monthIncome: mIn_tem.toFixed(2),
                monthBalance: mBal_tem.toFixed(2),
                isDisplay: false,
                isEmpty: true
              })
            }

            //将所有数据存储下来
            wx.setStorage({
              key: 'allData',
              data: newArr,
              success: (result) => { },
              fail: (e) => { console.error(e); },
            });
          })
          .catch(console.error);
        getApp().globalData.isFreash = false;                //全局置为false
      } else { }
    }

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '快来看帅哥做的记账本!!!',
      path: '/pages/index/index',
      // 设置转发的图片
      imageUrl: 'https://mp-f3b68706-562e-4e88-9436-5e8c05efc576.cdn.bspapp.com/cloudstorage/7ab9bb73-6f8d-4e85-8b9e-983561662fed.png',
      // 成功的回调
      success: (res) => {
        wx.showToast({
          title: '分享成功！',
          icon: 'success',
          duration: 1500,
        });
      },
      // 失败的回调
      fail: (res) => { },
      // 无论成功与否的回调
      complete: (res) => { }
    }
  }
})